import numpy as np


def pca(X, k):
    # 对 X 进行均值化处理
    X_mean = np.mean(X, axis=0)
    X_normalized = X - X_mean
    # 计算协方差矩阵
    cov_matrix = np.cov(X_normalized, rowvar=False)
    # 计算协方差矩阵的特征值和特征向量
    eigenvalues, eigenvectors = np.linalg.eig(cov_matrix)
    # 特征向量按特征值大小排列成矩阵, 取前 k 列构成投影矩阵 P
    sorted_indices = np.argsort(eigenvalues)[::-1]
    top_k_indices = sorted_indices[:k]
    P = eigenvectors[:, top_k_indices]
    # 计算降维后的数据
    reduced_data = np.dot(X_normalized, P)
    return reduced_data


if __name__ == '__main__':
    m, n, k = 5, 5, 3
    X = np.random.rand(m, n)
    print("降维前: \n", X)
    reduced_data = pca(X, k)
    print("降维后: \n", reduced_data)
